package lib.XML;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

import java.util.ArrayList;

import lib.Base.Message;

public class ConversationContentHandler implements ContentHandler {
	/**
	 * Class to handle XML content for conversation's
	 */
	private String currentValue;
	private ArrayList<Message> Conversation;

	private int time;
	private String UserId;
	private String Text;
	private boolean MessageFlag = false;

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		currentValue = new String(ch, start, length);
	}

	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		if (localName.equals("conversation")) {
			Conversation = new ArrayList<Message>();
		} else if (localName.equals("message")) {
			MessageFlag = true;
			time = Integer.parseInt(atts.getValue("time"));
		}
	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (localName.equals("userId")) {
			if (MessageFlag) {
				UserId = currentValue;
			}
		} else if (localName.equals("text")) {
			if (MessageFlag) {
				Text = currentValue;
			}
		} else if (localName.equals("message")) {
			if (MessageFlag) {
				Conversation.add(new Message(time, UserId, Text));
				time = 0;
				UserId = null;
				Text = null;
				MessageFlag = false;
			}
		}
	}

	public ArrayList<Message> getConversation() {
		return Conversation;
	}

	public void endDocument() throws SAXException {
	}

	public void endPrefixMapping(String prefix) throws SAXException {
	}

	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
	}

	public void processingInstruction(String target, String data)
			throws SAXException {
	}

	public void setDocumentLocator(Locator locator) {
	}

	public void skippedEntity(String name) throws SAXException {
	}

	public void startDocument() throws SAXException {
	}

	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
	}
}